﻿using System.Linq;
using System.Web.UI.WebControls;
using HNAlbum.Helper;
using HNAlbum.Logic.Entity;
using HNAlbum.Logic.Manager;

namespace HNAlbum.Component.AlbumGallery
{
    /// <summary>
    /// The dashboard where all albums are displayed
    /// </summary>
    public class Dashboard : Panel
    {

        /// <summary>
        /// With this layout, 12 items/page
        /// </summary>
        public const int ITEM_PER_PAGE = 12;

        #region Properties
        /// <summary>
        /// Number of items count in this dashboard instance
        /// </summary>
        public int ItemCount { get; set; }
        #endregion
        /// <summary>
        /// Build the dashboard
        /// <param name="pageIndex">Index of the page to show</param>
        /// <param name="guestMode">Build dashboard for guest</param>
        /// </summary>
        public Dashboard(int pageIndex, bool guestMode)
        {
            //Style setting
            this.Attributes.Add("id", "album_dashboard");

            //Create an instance of Album Manager
            AlbumManager albumMgr = new AlbumManager(true);
            //Demo mode
            if (guestMode)
            {
                //Get the demo album
                HNAlbumData demoAlbum = albumMgr.DemoAlbum;
                //Clear out all albums and only keep demo album
                albumMgr.AlbumCollection.Clear();
                albumMgr.AlbumCollection.Add(demoAlbum.Id, demoAlbum);
            }
            
            ItemCount = albumMgr.AlbumCollection.Count;

            //Max posible page count
            int pageCount = Function.GetPageCount(ITEM_PER_PAGE, ItemCount);
            if (pageIndex > pageCount) pageIndex = pageCount;

            //Calculate which albums to be displayed on this page
            int startItemIndex = (pageIndex - 1) * ITEM_PER_PAGE;
            int endItemIndex = startItemIndex + ITEM_PER_PAGE;
            if (endItemIndex > ItemCount)
            {
                endItemIndex = ItemCount;
            }

            //Loop and create album dashboard items
            for (int i = startItemIndex; i < endItemIndex;i++ )
            {
                HNAlbumData album = albumMgr.AlbumCollection.ElementAt(i).Value;
                album.Load();
                DashboardItem item = new DashboardItem(album);
                this.Controls.Add(item);
            }
        }
    }
}